package com.lanju.util;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.lanju.entity.User;
import com.lanju.service.JedisService;




public class SecurityContext {
	
	@Resource
	JedisService jedisService;
	 
	private static final String SECURITY_KEY = "__security_key";

	private static ThreadLocal contextHolder = new ThreadLocal();

	public static User getUser() {
		if (contextHolder.get() == null) {
			contextHolder.set(new User());
		}
		return (User) contextHolder.get();
	}

	public static void setUser(User u) {
		contextHolder.set(u);
	}

	public static void clearContext() {
		contextHolder.set(null);
	}

	public  static User getUserFromSession(HttpServletRequest request) {
		 Map<String, Object> map= null;
		HttpSession session = request.getSession(false);
		if (session == null)
			return null;
		Object o = session.getAttribute(SECURITY_KEY);
		if (o == null || !(o instanceof User))
			return null;
		return (User) o;
	}

	public static void saveUserToSeesion(User user, HttpServletRequest request, HttpServletResponse response) {
		saveUserToSeesion(user, request.getSession());
	}

	public static void logout(HttpServletRequest request) {
		HttpSession session = request.getSession();
		session.removeAttribute(SECURITY_KEY);
		session.invalidate();
		session = request.getSession(false);
		clearContext();
	}

	public static void saveUserToSeesion(User user, HttpSession sessoin) {
		if (user != null) {
			sessoin.setAttribute(SECURITY_KEY, user);
		}
	}

	public static void saveObjectToSession(String key, Object obj, HttpServletRequest request) {
		if (obj != null) {
			HttpSession session = request.getSession();
			session.setAttribute(key, obj);
		}
	}

	public static Object getObject(String key, HttpServletRequest request) {
		HttpSession session = request.getSession();
		return request.getAttribute(key);
	}
	

}
